from db import pg, namedata
from util import unixtime as epoch
from log import logging

class IllegalMove(Exception): pass

def getByEpoch(tableId,userId,minEpoch):
  pg.cursor.execute("SELECT id, color, value, x, y,is_moved,last_move_epoch FROM pieces WHERE table_id = %i AND last_move_epoch > %i ORDER BY last_move_epoch DESC"%( tableId, minEpoch))
  return namedata(pg.cursor.fetchall(),dbcolumns)

def getByTableId(tableId):
  pg.cursor.execute("SELECT id, color, value, x, y,  is_moved, last_move_epoch FROM pieces WHERE table_id = %i ORDER BY last_move_epoch ASC"%tableId)
  return namedata(pg.cursor.fetchall(),dbcolumns)

def move(pieceId,x,y,value):
  pg.cursor.execute("UPDATE pieces SET x = %i, y = %i, value = %i, is_moved = TRUE, last_move_epoch = %i WHERE id = %i"%(x,y,value,epoch(),pieceId))
  pg.connection.commit()
  
def remove(pieceId):
  pg.cursor.execute("DELETE FROM pieces WHERE id = %i"%pieceId)
  pg.connection.commit()
  
dbcolumns = ("id","color","value","x","y","is_moved","last_move_epoch")

